package com.xinyue.center.service;

import com.alibaba.nacos.common.utils.Md5Utils;
import com.xinyue.center.common.GameCenterError;
import com.xinyue.center.dao.AccountDao;
import com.xinyue.center.dao.entity.Account;
import com.xinyue.center.messages.request.LoginRequest;
import com.xinyue.center.messages.request.RegisterRequest;
import com.xinyue.center.service.manager.AccountLoginManager;
import com.xinyue.center.service.manager.AccountRegisterManager;
import com.xinyue.game.auth.AccountToken;
import com.xinyue.game.auth.JWTUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class AccountService implements IAccountService {

    private static final String FACTOR = "DXjdsdfsdfsdfserwefsdfgfsdfdswe";
    private static final String MD5_ENCODE = "utf8";

    @Autowired
    private AccountDao accountDao;
    @Autowired
    private StringRedisTemplate redisTemplate;

    private AccountLoginManager loginManager = new AccountLoginManager();
    private AccountRegisterManager registerManager = new AccountRegisterManager();

    private Logger logger = LoggerFactory.getLogger(AccountService.class);

    /**
     * <p>
     * Description:使用算法，根据用户名生成一个唯的ID
     * </p>
     *
     * @param username
     * @return
     * @author wang guang shuai
     * @date 2020年3月13日 下午3:39:24
     */
    public String generateAccountId(String username) {
        String value = username + username.toLowerCase() + "_" + username.toUpperCase();
        String newValue = Md5Utils.getMD5(value, MD5_ENCODE);
        String accountId = Md5Utils.getMD5((value + "_" + newValue), MD5_ENCODE);
        return accountId;
    }

    /**
     * 根据用户名和密码登陆
     *
     * @param loginRequest
     * @return
     * @author wgs
     * @date 2019年8月29日 下午8:24:29
     */
    @Override
    public Account login(LoginRequest loginRequest) {
        String userName = loginRequest.getUserName();
        String accountId = this.generateAccountId(userName);
        Optional<Account> accountOp = accountDao.findById(accountId, Account.class);
        if (accountOp.isPresent()) {
            Account account = accountOp.get();
            boolean isRight = loginManager.isPasswordRight(loginRequest.getPassword(), account.getPassword());
            if (isRight) {
                logger.debug("user {} 登陆成功", loginRequest.getUserName());
                return accountOp.get();
            } else {
                //返回登陆异常
                throw GameCenterError.PASSWORD_ERROR.newException("登陆账号:{}", loginRequest.getUserName());
            }
        } else {
            throw GameCenterError.ACCOUNT_NOT_EXIST.newException("登陆账号:{}", loginRequest.getUserName());
        }
    }

    @Override
    public Account register(RegisterRequest registerRequest) {
        registerManager.checkUsername(registerRequest.getUsername());
        registerManager.checkPassword(registerRequest.getRegisterIp());
        String accountId = this.generateAccountId(registerRequest.getUsername());
        Account account = registerManager.buildAccount(registerRequest, accountId);
        accountDao.saveOrUpdate(account);
        logger.info("注册成功:{},{}", account.getId(), account);
        return account;
    }

    @Override
    public String createUserToken(Account account) {
        AccountToken accountToken = new AccountToken();
        accountToken.setAccountId(account.getId());
        accountToken.updateExpireDays(30);
        return JWTUtil.createToken(accountToken);
    }

    @Override
    public Account selectAccount(String accountId) {
        return accountDao.findById(accountId, Account.class).orElse(null);
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.saveOrUpdate(account);
    }


}
